package cn.rkylin.oms.system.dictionary.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.system.dictionary.dao.DictDAOImpl;
import cn.rkylin.oms.system.dictionary.domain.OMS_DICT;
import cn.rkylin.oms.system.dictionary.service.IDictService;
import cn.rkylin.oms.system.dictionary.vo.DictVO;
import cn.rkylin.oms.system.project.vo.ProjectVO;

/**
 * 参数控制器
 *
 * @author sf
 * @version 1.0
 * @created 13-1月-2017 09:11:15
 */
@Controller
@RequestMapping("/dictionary")
public class DictController extends ApolloController {
    private static final Log logger = LogFactory.getLog(DictController.class);
    // 常量定义
    private static final String PAGE_SELECT_STATEMENT = "pageSelectShop"; // 分页语句Statement名称
    private static final String GOTO_DICT_LIST = "/system/organization/dict/DictList"; // 跳转到店铺列表页

    /**
     * 参数服务层
     */
    @Autowired
    private IDictService dictService;

    /**
     * 构造函数
     */
    public DictController() {

    }

    /**
     * 跳转到参数列表
     */
    @RequestMapping(value = "/gotoDictList")
    public String gotoDictList() {
        return GOTO_DICT_LIST;
    }

    /**
     * 方法简要描述信息.
     * <p>
     * 描述: 根据查询条件获取参数
     * </p>
     * <p>
     * 备注: 详见顺序图<br>
     * </p>
     * 
     * @param mapping
     *            - Struts的ActionMapping对象，包含了请求映射的基本信息。
     * @param form
     *            - Struts的ActionForm对象，包含了请求页面要提交的数据(只在配置了FormBean标签时有效)
     * @throws 无
     */
    @ResponseBody
    @RequestMapping(value = "/dictList", method = RequestMethod.GET)
    public Map<String, Object> getDictList(String quickSearch, DictVO dict, String formJson,
            @RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "10") int length)
            throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 前台搜索条件，此处只有一个角色名称
            DictVO param = new DictVO();
            if (quickSearch != null) {
                quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
                if (StringUtils.isNotEmpty(quickSearch)) {
                    param.setSearchCondition(quickSearch);
                }
            }
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;
            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("validateStatus", "validate");
            replaceFieldsMap.put("status", "enable");
            // 排序语句生成
            String orderStatement = getOrderString(DictDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }
            param.setDeleted("n");
            // 获取分页数据
            PageInfo<DictVO> dictVOList = dictService.findByWhere(page, length, param);
            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RECORDS_FILTERED, dictVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, dictVOList.getTotal());
            returnMap.put(RETURN_DATA, dictVOList.getList());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 方法简要描述信息.
     * <p>
     * 描述: 添加参数
     * </p>
     * <p>
     * 备注: 详见顺序图<br>
     * </p>
     * 
     * @param mapping
     *            - Struts的ActionMapping对象，包含了请求映射的基本信息。
     * @param form
     *            - Struts的ActionForm对象，包含了请求页面要提交的数据(只在配置了FormBean标签时有效)
     * @throws 无
     */
    @ResponseBody
    @RequestMapping(value = "/addDict")
    @SystemControllerLog(module = "系统参数", operation = "添加参数", keyCode = "dictId")
    public Map<String, Object> addDict(@RequestBody DictVO dictVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            DictVO dictVO2 = new DictVO();
            dictVO2.setDictCode(dictVO.getDictCode());
            dictVO2.setDeleted("n");
            List<DictVO> dictVOList = dictService.getDictByCondition(dictVO2);
            if (dictVOList.size() >= 1) {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "该内部编码已存在");
                return returnMap;
            }
            dictVO.setDeleted("n");
            dictVO.setDictId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
            dictService.insert(dictVO);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {

            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
            System.out.println(ex);
            System.out.println(returnMap);
        }
        returnMap.put("dictId", dictVO.getDictId());
        return returnMap;
    }

    /**
     * 方法简要描述信息.
     * <p>
     * 描述: 删除参数
     * </p>
     * <p>
     * 备注: 详见顺序图<br>
     * </p>
     * 
     * @param mapping
     *            - Struts的ActionMapping对象，包含了请求映射的基本信息。
     * @param form
     *            - Struts的ActionForm对象，包含了请求页面要提交的数据(只在配置了FormBean标签时有效)
     * @throws 无
     */
    @ResponseBody
    @RequestMapping(value = "/deleteDict")
    @SystemControllerLog(module = "系统参数", operation = "删除参数", keyCode = "dictId")
    public Map<String, Object> deleteDict(String dictId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            dictService.delete(dictId);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("dictId", dictId);
        return returnMap;
    }

    /**
     * 方法简要描述信息.
     * <p>
     * 描述: 修改参数
     * </p>
     * <p>
     * 备注: 详见顺序图<br>
     * </p>
     * 
     * @param mapping
     *            - Struts的ActionMapping对象，包含了请求映射的基本信息。
     * @param form
     *            - Struts的ActionForm对象，包含了请求页面要提交的数据(只在配置了FormBean标签时有效)
     * @throws 无
     */
    @ResponseBody
    @RequestMapping(value = "/updateDict")
    @SystemControllerLog(module = "系统参数", operation = "删除参数", keyCode = "dictId")
    public Map<String, Object> updateDict(@RequestBody DictVO dictVO) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            String code = dictVO.getDictCode();
            String dicUpdateCode = dictVO.getDicUpdateCode();
            if (!code.equals(dicUpdateCode)) {
                DictVO dictVO2 = new DictVO();
                dictVO2.setDictCode(code);
                List<DictVO> dictVOList = dictService.getDictByCondition(dictVO2);
                if (dictVOList.size() >= 1) {
                    returnMap.put(JSON_RESULT, FAILED);
                    returnMap.put(JSON_MSG, "该内部编码已存在");
                    return returnMap;
                }
            }
            dictService.update(dictVO);
            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("dictId", dictVO.getDictId());
        return returnMap;
    }

    /**
     * 获取参数类型
     * 
     * @param
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getDictTypeList", method = RequestMethod.GET)
    public Map<String, Object> getDictTypeList() throws Exception {
        /// 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            List list = dictService.getDictTypeList(new OMS_DICT());
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, list);
            return returnMap;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 获取客户端类型
     * 
     * @param
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getParamDictByCode", method = RequestMethod.GET)
    public Map<String, Object> getDictValueType(String code) throws Exception {
        /// 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null || currentUser.getCurrentProject() == null) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(RETURN_DATA, new ArrayList<>());
            returnMap.put(JSON_MSG, "您没有项目权限");
            return returnMap;
        }

        OMS_DICT dict = new OMS_DICT();
        dict.setDictCode(code);
        try {
            List list = dictService.getParamDictByCode(dict);
            ProjectVO userCurrentProject = currentUser.getCurrentProject();
            if ("bi_dashboard_url".equals(code)) {
                if (userCurrentProject != null && "瑞金麟品牌直销店".equals(userCurrentProject.getPrjName())) {
                    returnMap.put(RETURN_DATA, list);
                } else {
                    returnMap.put(RETURN_DATA, new ArrayList<>());
                }
            } else {
                returnMap.put(RETURN_DATA, list);
            }
            returnMap.put(JSON_RESULT, SUCCESS);
            return returnMap;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

}